package com.xinyi.tangmi;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Handler;
import android.util.Log;

public class GetGenItems {
	public static final String BASE_URL = "http://www.youyouyiku.com/api/";
	public static final String PIC_URL = "http://www.youyouyiku.com/";
	List<AutoMatchItem> items;
	private String PATH;
	private Handler handler;
	RequestContent requestContent;

	public GetGenItems(SecondClass requestContent, final Handler handler,
			int page) throws Exception {
		// TODO Auto-generated constructor stub
		String body = requestContent.getUrl();
		this.handler = handler;
		PATH = BASE_URL + body + "&page=" + page + "&page_size="
				+ MainActivity.GEN_PAGE_SIZE + "&attr_color="
				+ MainActivity.requestContent.color + "&attr_temp="
				+ MainActivity.requestContent.temp + "&price_min="
				+ MainActivity.requestContent.price_min + "&price_max="
				+ MainActivity.requestContent.price_max;
		;
		Log.i("path", PATH);
	}

	public List<GenItem> getItems() {
		List<GenItem> items = new ArrayList<GenItem>();
		try {
			JSONObject jsonObject = readJason(PATH, handler);
			Log.i("PAHT", jsonObject.toString());
			JSONObject object;
			JSONArray jsonArray = jsonObject.getJSONArray("obj");
			for (int i = 0; i < jsonArray.length();) {
				GenItem item = new GenItem();
				object = (JSONObject) jsonArray.get(i);
				item.setImageUrl(object.getString("goods_thumb"));
				item.setShopPrice(object.getString("shop_price"));
				item.setItemName(object.getString("name"));
				item.setMarketPrice(object.getString("market_price"));
				item.setUrl(object.getString("url"));
				items.add(item);
				i++;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return items;

	}

	public JSONObject readJason(String urlString, Handler handler)
			throws Exception {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		URL url = new URL(urlString);
		HttpURLConnection hUrlConnection = (HttpURLConnection) url
				.openConnection();
		if (hUrlConnection.getResponseCode() == 200) {
			InputStream inputStream = hUrlConnection.getInputStream();
			Log.i("code", hUrlConnection.getResponseCode() + "");
			int len = 0;
			while ((len = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len);
			}
			inputStream.close();
			byte[] bytes = byteArrayOutputStream.toByteArray();
			JSONObject jsonObject = new JSONObject(new String(bytes));
			return jsonObject;
		}
		return null;

	}

}